package com.fushenlan.epidemicControl.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.fushenlan.Vo.BuildInfoVo;
import com.fushenlan.Vo.InhabitInfoVo;
import com.fushenlan.commons.ApiGlobalErrorDefinition;
import com.fushenlan.commons.GeneralResponse;
import com.fushenlan.epidemicControl.config.JwtUtil;
import com.fushenlan.epidemicControl.dto.BuildingInfoDto;
import com.fushenlan.epidemicControl.dto.InhabitantInfoDto;
import com.fushenlan.epidemicControl.service.BuildingInfoService;
import com.fushenlan.epidemicControl.service.InhabitantInfoService;
import com.fushenlan.helper.ListPageHelper;
import com.fushenlan.po.BuildingInfo;
import com.fushenlan.po.PageInfoVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author XUJIN
 * @DATE 2022/4/21
 * @PACKAGE_NAME com.fushenlan.epidemicControl.controller
 * @VERSION 1.0
 * 基础信息管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/basic")
@Api(value = "基础信息管理控制器", description = "基础信息管理控制器", tags = "basic-controller")
public class BasicInfoController {



    @Autowired
    private BuildingInfoService buildingInfoService;

    @Autowired
    private InhabitantInfoService inhabitantInfoService;

    /**
     * 登录人居民表id
     */
    private static final String NEIGHOBRHOOD_ID = "neighborhoodId";  //当前登录用户所属居委会id

    /**
     * 通过条件查询楼栋列表
     * @param
     * @param
     * @param
     * @return
     */
    @GetMapping("/getBuildList")
    @ApiOperation(value = "根据条件查询居委下属楼栋列表")
    public GeneralResponse getBuildList(BuildingInfoDto buildingInfoDto, int pageNo, int pageSize) {
        // TODO: 2022/4/23 分页待完善
        try {
            //获取当前登录居委id
            String userInfo = JwtUtil.getUserInfo(NEIGHOBRHOOD_ID);
            if (StrUtil.isEmpty(userInfo)){
                return GeneralResponse.fail(ApiGlobalErrorDefinition.TOKEN_EXPIRED);
            }
            buildingInfoDto.setParentId(Integer.valueOf(userInfo));
            PageHelper.startPage(pageNo,pageSize);
            List<BuildInfoVo> buildList = buildingInfoService.findBuildList(buildingInfoDto);
            PageInfo<BuildInfoVo> pageInfo = new PageInfo<BuildInfoVo>(buildList);
            PageInfoVo pageDateInfoVo = ListPageHelper.StartPage(pageInfo);
            return GeneralResponse.success(pageDateInfoVo);
        } catch (Exception e) {
            log.error("服务器异常==>{}",e);
            return GeneralResponse.fail();
        }
    }


    /**
     * 获取下级区域
     * @param parentId
     * @param level
     * @return
     */
    @GetMapping("/getSubBuildList")
    @ApiOperation(value = "根据楼栋level级别及parentId获取楼栋信息(小区的上级parentId为居委会表id)")
    public GeneralResponse getBuildList(Integer parentId,Integer level) {

        BuildingInfo buildingInfo = new BuildingInfo();
        //获取如果level=1 则其上级为居委会id,特殊处理
        if (parentId == null && level == 1){
            String userInfo = JwtUtil.getUserInfo(NEIGHOBRHOOD_ID);
            buildingInfo.setParentId(Integer.valueOf(userInfo));
        }else {
            buildingInfo.setParentId(parentId)
                         .setLevel(level);
        }
        List<BuildingInfo> buildInfoList = buildingInfoService.findBuildInfoList(buildingInfo);
        return GeneralResponse.success(buildInfoList);
    }



    @PostMapping("/addBuildingInfo")
    @ApiOperation(value = "添加楼栋信息", notes = "添加楼栋信息")
    public GeneralResponse addBuildingInfo(@ApiParam(value = "楼栋信息,如x单元", required = true) @RequestParam String buildNo,
                                          @ApiParam(value = "房间号,如xxx室", required = true) @RequestParam String roomNo,
                                          @ApiParam(value = "小区名称,xx小区", required = true) @RequestParam String communityName
                                          ) {
        try {
            //获取当前登录居委会
            String userInfo = JwtUtil.getUserInfo(NEIGHOBRHOOD_ID);
            if (StrUtil.isEmpty(userInfo)){
                return GeneralResponse.fail(ApiGlobalErrorDefinition.TOKEN_EXPIRED);
            }
           return buildingInfoService.addBuildingInfo(Integer.valueOf(userInfo),communityName,buildNo,roomNo);
        }catch (Exception e){
            log.error("======》添加楼栋信息错误 {}",e);
            return GeneralResponse.fail();
        }
    }

    @PostMapping("/delBuildingInfo")
    @ApiOperation(value = "删除楼栋信息", notes = "删除楼栋信息")
    public GeneralResponse delBuildingInfo(@ApiParam(value = "楼栋表id", required = true) @RequestParam Integer id) {

        if (id == null){
            return GeneralResponse.fail(ApiGlobalErrorDefinition.NOT_SELECT);
        }
        try {
            buildingInfoService.deleteBuildinginfo(id);
            return GeneralResponse.success();
        }catch (Exception e){
            log.error("======》删除楼栋信息 {}",e);
            return GeneralResponse.fail();
        }
    }


    @PostMapping("/updateBuildingInfo")
    @ApiOperation(value = "更新楼栋信息", notes = "更新楼栋信息")
    public GeneralResponse updateBuildingInfo(@ApiParam(value = "楼栋表id 即", required = true)  Integer id,
                                             @ApiParam(value = "楼栋信息,如x单元")  String buildNo,
                                             @ApiParam(value = "房间号,如xxx室")  String roomNo,
                                             @ApiParam(value = "小区名称,xx小区")  String communityName) {

        if (id == null){
            return GeneralResponse.fail(ApiGlobalErrorDefinition.NOT_SELECT);
        }
        try {
            return buildingInfoService.updateBuildingInfo(id,communityName,buildNo,roomNo);
        }catch (Exception e){
            log.error("======》添加楼栋信息错误 {}",e);
            return GeneralResponse.fail();
        }
    }




    @GetMapping("/getInhabitList")
    @ApiOperation(value = "获取居民列表")
    public GeneralResponse getinhabitList(InhabitantInfoDto inhabitantInfoDto,int pageNo,int pageSize) {
        // TODO: 2022/4/23 分页待完善
        try {
            //获取当前登录的居委会id
            String userInfo = JwtUtil.getUserInfo(NEIGHOBRHOOD_ID);
            if (StrUtil.isEmpty(userInfo)){
                return GeneralResponse.fail(ApiGlobalErrorDefinition.TOKEN_EXPIRED);
            }
            inhabitantInfoDto.setNeighborhoodId(Integer.valueOf(userInfo));
            PageHelper.startPage(pageNo,pageSize);
            List<InhabitInfoVo> inhabitList = inhabitantInfoService.findInhabitList(inhabitantInfoDto);
            //分页
            PageInfo<InhabitInfoVo> pageInfo = new PageInfo<InhabitInfoVo>(inhabitList);
            PageInfoVo pageInfoVo = ListPageHelper.StartPage(pageInfo);
            pageInfoVo.setNotRegistedNum(inhabitantInfoService.getNotRegisterInhabitNum(Integer.valueOf(userInfo)));
            return GeneralResponse.success(pageInfoVo);
        } catch (Exception e) {
            log.error("服务器异常===>{}",e);
            return GeneralResponse.fail();
        }

    }


    @GetMapping("/getFamilylist")
    @ApiOperation(value = "getFamilylist")
    public GeneralResponse getFamilylist(InhabitantInfoDto infoDto) {
        try {
            //获取当前登录的居委会id
            if (infoDto.getNeighborhoodId() == null){
                String userInfo = JwtUtil.getUserInfo(NEIGHOBRHOOD_ID);
                infoDto.setNeighborhoodId(Integer.valueOf(userInfo));
            }
            // TODO: 2022/5/4 修复本人与家庭成员重复 
            List<InhabitInfoVo> familylist = inhabitantInfoService.getFamilylist(infoDto);
            //修改本人，附带家庭成员
            List<InhabitInfoVo> collect = new ArrayList<>();
            if (infoDto.getFamilyId() == 0){
                collect = familylist.stream().filter(tmp -> tmp.getFamilyId() != 0).collect(Collectors.toList());
            }else {
                InhabitantInfoDto inh = new InhabitantInfoDto();
                inh.setFamilyId(infoDto.getFamilyId());
                //获取有公共的上级id家庭成员
                List<InhabitInfoVo> collect1 = inhabitantInfoService.findInhabitList(inh).stream().filter(tmp -> Long.valueOf(tmp.getId()) != infoDto.getId()).collect(Collectors.toList());
                //查询最上级的成员
                InhabitantInfoDto mostLevel = new InhabitantInfoDto();
                mostLevel.setId(Long.valueOf(inh.getFamilyId()));
                List<InhabitInfoVo> inhabitList = inhabitantInfoService.findInhabitList(mostLevel);
                if (CollectionUtil.isNotEmpty(inhabitList)){
                    collect1.add(inhabitList.get(0));
                }
                collect.addAll(collect1);
            }
            return GeneralResponse.success(collect);
        } catch (Exception e) {
            log.error("服务器异常===>{}",e);
            return GeneralResponse.fail();
        }

    }


    /**
     * 获取居民信息列表，如有家庭成员，一同展示
     * @return
     */
    @PostMapping("/batchModifyInhabit")
    @ApiOperation(value = "batchModifyInhabit")
    public GeneralResponse batchModifyInhabit(@RequestBody  List<InhabitantInfoDto> list) {
        // TODO: 2022/4/23 分页待完善
        GeneralResponse generalResponse = new GeneralResponse();
        try {
            generalResponse = inhabitantInfoService.batchModifyInhabit(list);
            return generalResponse;
        } catch (Exception e) {
            log.error("服务器异常===>{}",e);
            return GeneralResponse.fail();
        }

    }


    @PostMapping("/addInhabitInfo")
    @ApiOperation(value = "添加居民信息", notes = "添加居民信息")
    public GeneralResponse addInhabitInfo(InhabitantInfoDto inhabitantInfoDto) {

        try {
            //获取当前登录的居委会id
            if (inhabitantInfoDto.getNeighborhoodId() == null){
                String userInfo = JwtUtil.getUserInfo(NEIGHOBRHOOD_ID);
                inhabitantInfoDto.setNeighborhoodId(Integer.valueOf(userInfo));
            }
            return inhabitantInfoService.addInhabitInfo(inhabitantInfoDto);
        }catch (Exception e){
            log.error("======》添加用户息错误 {}",e);
            return GeneralResponse.fail();
        }
    }


    @PostMapping("/updateInhabitInfo")
    @ApiOperation(value = "更新居民信息", notes = "更新居民信息")
    public GeneralResponse updateInhabitInfo(InhabitantInfoDto inhabitantInfoDto) {

        if (inhabitantInfoDto.getId() == null){
            return GeneralResponse.fail(ApiGlobalErrorDefinition.NOT_SELECT);
        }

        //获取当前登录的居委会id
        if (inhabitantInfoDto.getNeighborhoodId() == null){
            String userInfo = JwtUtil.getUserInfo(NEIGHOBRHOOD_ID);
            inhabitantInfoDto.setNeighborhoodId(Integer.valueOf(userInfo));
        }

        try {
            return inhabitantInfoService.updateInhabitInfo(inhabitantInfoDto);
        }catch (Exception e){
            log.error("======》添加用户息错误 {}",e);
            return GeneralResponse.fail();
        }
    }


    @PostMapping("/delInhabitInfo")
    @ApiOperation(value = "删除居民信息", notes = "删除居民信息")
    public GeneralResponse delInhabitInfo(@ApiParam(value = "居民id", required = true) @RequestParam Integer id) {

        if (id == null){
          return GeneralResponse.fail(ApiGlobalErrorDefinition.NOT_SELECT);
        }
        try {
            inhabitantInfoService.deleteInhabitinfo(id);
            return GeneralResponse.success();
        }catch (Exception e){
            log.error("======》删除居民信息失败 {}",e);
            return GeneralResponse.fail();
        }
    }


    /**
     * 下载导入楼栋列表信息列表excel
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "/downloadBuildModel")
    @ApiOperation(value = "下载楼栋excel列表",notes = "下载楼栋excel列表")
    public void downloadBuildModel(HttpServletResponse response) throws IOException {
        List<BuildInfoVo> buildInfoVoList = new ArrayList<>();
        BuildInfoVo buildInfoVo = new BuildInfoVo();
        buildInfoVo.setCommunityName("例如：荣成小区")
                   .setBuildNo("例如：A栋")
                   .setRoomNo("例如：403室");
        buildInfoVoList.add(buildInfoVo);

        // 导出数据，数据，数据类型，响应对象文件名称
        buildingInfoService.downloadBuildModel(buildInfoVoList,response);
    }


    /**
     *
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "/exportBuildList")
    @ApiOperation(value = "导出楼栋数据至excel中")
    public void exportBuildList(HttpServletResponse response) throws IOException {
        // 导出数据，数据，数据类型，响应对象文件名称
        //获取当前登录的居委会id
        String userInfo = JwtUtil.getUserInfo(NEIGHOBRHOOD_ID);
        buildingInfoService.exportBuildInfo(Integer.valueOf(userInfo),response);
    }

    /**
     *
     * @param response
     * @throws IOException
     */
    @PostMapping(value = "/uploadBuildList")
    @ApiOperation(value = "导入楼栋列表数据")
    public GeneralResponse uploadBuildList(@ApiParam(value = "文件对象") @RequestParam("file") MultipartFile multipartFile, HttpServletResponse response) throws IOException {

        String userInfo = JwtUtil.getUserInfo(NEIGHOBRHOOD_ID);
        if (StrUtil.isEmpty(userInfo)){
            return GeneralResponse.fail(ApiGlobalErrorDefinition.TOKEN_EXPIRED);
        }
        // 导出数据，数据，数据类型，响应对象文件名称
        try {
            buildingInfoService.uploadBuildList(Integer.valueOf(userInfo),multipartFile,response);
        } catch (Exception e) {
            log.error("读取文件异常====>{}",e);
            return GeneralResponse.fail();
        }
        return GeneralResponse.success();
    }

    @GetMapping(value = "/uploadTest")
    public GeneralResponse uploadTest(@RequestParam("neighborId") Integer neighborId, HttpServletResponse response) throws IOException {

        try {
            //楼栋测试
            // buildingInfoService.uploadBuildList(neighborId,null,response);
            //居民
            inhabitantInfoService.uploadInhabitList(neighborId,null,response);
        } catch (Exception e) {
            e.printStackTrace();
            return GeneralResponse.fail();
        }
        return GeneralResponse.success();
    }



    /**
     * 下载居民列表excel模板excel
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "/downloadinhbatModel")
    @ApiOperation(value = "下载居民excel模板", notes = "下载居民excel模板")
    public void downloadinhbatModel(HttpServletResponse response) throws IOException {
        List<InhabitInfoVo> inhabitInfoVos = new ArrayList<>();
        InhabitInfoVo inhabitInfoVo = new InhabitInfoVo();
        inhabitInfoVo.setIdentifyNo("例如:36xxx32")
                     .setIdentifyType(2)
                     .setPhoneNumber("150xxxx")
                     .setUserName("徐xx");
        inhabitInfoVos.add(inhabitInfoVo);

        // 导出数据，数据，数据类型，响应对象文件名称
        inhabitantInfoService.downloadInhbitModel(inhabitInfoVos,response);
    }


    /**
     *
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "/exportInhabitList")
    @ApiOperation(value = "导出居民数据至excel", notes = "导出居民信息")
    public void exportInhabitList(HttpServletResponse response) throws IOException {
        // 导出数据，数据，数据类型，响应对象文件名称
        String userInfo = JwtUtil.getUserInfo(NEIGHOBRHOOD_ID);
        inhabitantInfoService.exportInhabitInfo(Integer.valueOf(userInfo),response);
    }



    /**
     *
     * @param response
     * @throws IOException
     */
    @PostMapping(value = "/uploadInfoList")
    @ApiOperation(value = "导入居民excel", notes = "导入居民信息")
    public GeneralResponse uploadInfoList(@ApiParam(value = "文件对象", required = true)@RequestParam("file") MultipartFile multipartFile,HttpServletResponse response) throws IOException {


        String userInfo = JwtUtil.getUserInfo(NEIGHOBRHOOD_ID);
        if (StrUtil.isEmpty(userInfo)){
            return GeneralResponse.fail(ApiGlobalErrorDefinition.TOKEN_EXPIRED);
        }
        // 导出数据，数据，数据类型，响应对象文件名称
        try {
            inhabitantInfoService.uploadInhabitList(Integer.valueOf(userInfo),multipartFile,response);

        } catch (Exception e) {
            log.error("读取文件异常====>{}",e);
            return GeneralResponse.fail();
        }
        return GeneralResponse.success();
    }




}
